<template>
  <div class="activity-manager">
    <!-- 搜索和操作栏 -->
    <div class="action-bar">
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="请输入活动名称搜索"
          class="search-input"
          clearable
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch" class="search-btn">
          搜索
        </el-button>
      </div>
      <el-button type="primary" @click="showCreateDialog" class="create-btn">
        <el-icon><Plus /></el-icon>新增活动
      </el-button>
    </div>

    <!-- 活动列表表格 -->
    <el-table
      :data="activities"
      stripe
      border
      class="activity-table"
      v-loading="loading"

    >
      <el-table-column prop="title" label="活动名称" min-width="200" align="center" >
        <template #default="{ row }">
          <el-link type="primary" @click="viewActivityDetail(row.id)">
            {{ row.title }}
          </el-link>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="活动图片" min-width="300" align="center">

        <template #default="{ row }">
          <el-image
            :src="row.coverImg"
            :preview-src-list="[row.coverImg]"
            fit="contain"
            style="width: 60px; height: 60px;"
          />
        </template>

      </el-table-column>

      <el-table-column prop="content" label="活动内容" min-width="300">
        <template #default="{ row }">
          <el-text class="content-text" :truncated="true">
            {{ row.description }}
          </el-text>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="活动地址" width="200">
        <template #default="{ row }">
          <el-text class="content-text" :truncated="true">
            {{ row.location }}
          </el-text>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="活动类型" width="200">
        <template #default="{ row }">
          <el-text class="content-text" :truncated="true">
            {{ row.activityTypeName }}
          </el-text>
        </template>
      </el-table-column>

      <el-table-column prop="content" label="招募人数" width="100">
        <template #default="{ row }">
          <el-text class="content-text" :truncated="true">
            {{ row.registeredNumber }}
          </el-text>
        </template>
      </el-table-column>



      <el-table-column prop="content" label="报名人数" width="100">
        <template #default="{ row }">
          <el-text class="content-text" :truncated="true">
            {{ row.signUpNumber }}
          </el-text>
        </template>
      </el-table-column>

      <el-table-column prop="startTime" label="开始时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.startTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="结束时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" link @click="editActivity(row)">
              编辑
            </el-button>

            <el-button type="danger" link @click="handleDeleteActivity(row)">
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 创建/编辑活动对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '创建活动' : '编辑活动'"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="activityFormRef"
        :model="activityForm"
        :rules="activityRules"
        label-width="100px"
        class="activity-form"
      >
        <el-form-item label="活动名称" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入活动名称" />
        </el-form-item>
        <el-form-item label="活动类型" prop="activityTypeId">
          <el-select v-model="activityForm.activityTypeId" placeholder="请选择活动类型">
            <el-option
              v-for="type in activityTypeList"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="活动图片" prop="coverImg">
          <el-upload
            class="avatar-uploader"
            action="/api/api/admin/activity/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="activityForm.coverImg" :src="activityForm.coverImg" class="avatar" style="width: 100px; height: 100px;" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动内容" prop="description">
          <el-input
            v-model="activityForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动内容"
          />
        </el-form-item>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="activityForm.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[
              new Date(2000, 1, 1, 8, 0, 0),
              new Date(2000, 1, 1, 17, 0, 0)
            ]"
            :shortcuts="dateShortcuts"
            :disabled-date="disabledDate"
            @change="handleTimeChange"
          />
        </el-form-item>
        <el-form-item label="活动地点" prop="location">
          <el-input v-model="activityForm.location" placeholder="请输入活动地点" />
        </el-form-item>
        <el-form-item label="招募人数" prop="registeredNumber">
          <el-input-number
            v-model="activityForm.registeredNumber"
            :min="1"
            :max="1000"
            placeholder="请输入最大招募人数"
          />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitActivity">
            {{ dialogType === 'create' ? '创建' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatDateTime } from '@/utils/format'
import { getActivityList, addActivity, updateActivity, deleteActivity as removeActivity } from '@/api/admin/activity'

import { getActivityTypeList } from '@/api/admin/activityType'
import { useRouter } from 'vue-router'

// 搜索查询
const searchQuery = ref('')
// 加载状态
const loading = ref(false)
// 活动列表数据
const activities = ref([])
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const activityFormRef = ref(null)
const activityForm = ref({
  title: '',
  activityTypeId: '',
  coverImg: '',
  description: '',
  timeRange: [],
  location: '',
  maxParticipants: 50,
  credits: 1
})

// 表单验证规则
const activityRules = {
  title: [
    { required: true, message: '请输入活动名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  activityTypeId: [
    { required: true, message: '请选择活动类型', trigger: 'change' }
  ],
  coverImg: [
    { required: true, message: '请上传活动图片', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' },
    { min: 10, max: 2000, message: '长度在 10 到 2000 个字符', trigger: 'blur' }
  ],
  timeRange: [
    { type: 'array', required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  location: [
    { required: true, message: '请输入活动地点', trigger: 'blur' }
  ],
  maxParticipants: [
    { required: true, message: '请输入最大报名人数', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请输入活动积分', trigger: 'blur' }
  ]
}

const router = useRouter()

// 获取活动列表
const getActivities = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: searchQuery.value
    }
    const { data } = await getActivityList(params)
    if (data) {
      activities.value = data.records || []
      total.value = data.total || 0
      // 如果当前页没有数据且不是第一页，则回到上一页
      if (data.records && data.records.length === 0 && currentPage.value > 1) {
        currentPage.value--
        await getActivities()
      }
    } else {
      activities.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
    activities.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置为第一页
  getActivities()
}

// 显示创建对话框
const showCreateDialog = () => {
  dialogType.value = 'create'
  activityForm.value = {
    title: '',
    activityTypeId: '',
    coverImg: '',
    description: '',
    timeRange: [],
    location: '',
    maxParticipants: 50,
    credits: 1
  }
  dialogVisible.value = true
}

// 编辑活动
const editActivity = (row) => {
  dialogType.value = 'edit'
  activityForm.value = {
    ...row,
    activityTypeId: row.activityTypeId,
    coverImg: row.coverImg,
    timeRange: [row.startTime, row.endTime],
    id: row.id
  }
  dialogVisible.value = true
}

// 查看活动详情
const viewActivityDetail = (id) => {
  router.push(`/admin/activity/detail/${id}`)
}

// 查看报名情况
const viewRegistrations = (row) => {
  router.push(`/admin/activity/${row.id}/registrations`)
}

// 删除活动
const handleDeleteActivity = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该活动吗？删除后无法恢复。',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    await removeActivity(row.id)
    ElMessage.success('删除成功')
    getActivities()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 提交活动表单
const submitActivity = async () => {
  if (!activityFormRef.value) return

  await activityFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        const formData = {
          ...activityForm.value,
          startTime: activityForm.value.timeRange[0],
          endTime: activityForm.value.timeRange[1]
        }
        delete formData.timeRange

        if (dialogType.value === 'create') {
          await addActivity(formData)
          ElMessage.success('创建成功')
        } else {
          await updateActivity(formData)
          ElMessage.success('更新成功')
        }

        dialogVisible.value = false
        getActivities()
      } catch (error) {
        console.error('提交活动失败:', error)
        ElMessage.error('提交失败')
      }
    } else {
      console.error('表单验证失败:', fields)
    }
  })
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // 切换每页显示数量时重置为第一页
  getActivities()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getActivities()
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'info',    // 草稿
    1: 'success', // 进行中
    2: 'warning', // 已结束
    3: 'danger'   // 已取消
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '进行中',
    2: '已结束',
    3: '已取消'
  }
  return statusMap[status] || '未知'
}

// 在 script setup 部分添加以下代码
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() + 3600 * 1000 * 24)
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() + 3600 * 1000 * 24)
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() + 3600 * 1000 * 24)
      end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7 // 禁用今天之前的日期
}

// 处理时间变化
const handleTimeChange = (value) => {
  if (value) {
    const [start, end] = value
    // 验证开始时间是否小于结束时间
    if (new Date(start) >= new Date(end)) {
      ElMessage.warning('开始时间必须小于结束时间')
      activityForm.value.timeRange = []
      return
    }

    // 验证时间范围是否合理（例如不超过一年）
    const oneYear = 365 * 24 * 60 * 60 * 1000
    if (new Date(end) - new Date(start) > oneYear) {
      ElMessage.warning('活动时间范围不能超过一年')
      activityForm.value.timeRange = []
      return
    }
  }
}

// 获取活动类型列表
const activityTypeList = ref([])

// 组件挂载时获取数据
onMounted(async () => {
  getActivities()
  // 获取活动类型列表
  const { data } = await getActivityTypeList()
  activityTypeList.value = data || []
})

const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    activityForm.value.coverImg = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.msg || '上传失败')
  }
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件')
  }
  return isImage
}
</script>

<style lang="scss" scoped>
.activity-manager {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    background: white;
    padding: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .search-section {
      display: flex;
      gap: 10px;
      flex: 1;
      max-width: 500px;

      .search-input {
        width: 300px;
      }
    }

    .create-btn {
      display: flex;
      align-items: center;
      gap: 5px;
    }
  }

  .activity-table {
    background: white;
    border-radius: 8px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .content-text {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    :deep(.el-button) {
      padding: 4px 8px;
    }
  }
  :deep(.el-pagination) {
    float: right;
  }

  //.pagination-container {
  //  display: flex;
  //  justify-content: flex-end;
  //  margin-top: 20px;
  //  padding: 16px;
  //  background: white;
  //  border-radius: 8px;
  //  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  //}

  .activity-form {
    .el-date-picker {
      width: 100%;
    }

    .el-form-item {
      margin-bottom: 20px;
    }
  }
}

// 响应式设计
@media screen and (max-width: 768px) {
  .activity-manager {
    padding: 10px;

    .action-bar {
      flex-direction: column;
      gap: 10px;
      padding: 10px;

      .search-section {
        width: 100%;
        max-width: none;

        .search-input {
          width: 100%;
        }
      }

      .create-btn {
        width: 100%;
      }
    }

    .activity-table {
      :deep(.el-table__header) {
        display: none;
      }

      :deep(.el-table__body) {
        td {
          display: block;
          width: 100%;
          border: none;
          padding: 5px 10px;

          &:before {
            content: attr(data-label);
            font-weight: bold;
            display: inline-block;
            width: 100px;
          }
        }

        tr {
          display: block;
          border-bottom: 1px solid #EBEEF5;
          margin-bottom: 10px;
        }
      }
    }
  }
}


</style>
